﻿using BootstrapBlazor.Components;
using Microsoft.AspNetCore.SignalR.Client;
using System.ComponentModel.DataAnnotations;
using TrackSystem.Entities.Attr;
using TrackSystem.IO.Logics;
using TrackSystem.IO.Loops;

namespace TrackSystem.UI.Server.Pages.IOControl
{
    public partial class LoopControlPage
    {
        [Required]
        private HubConnection? _hubIo;

        private string _message = "无信息";

        private LoopItem? _loopItem;
        private List<SelectedItem> loopNameItems { get; set; } = [];
        private bool _bFirst = true;

        private string? CurrentLoopName;

        /// <summary>
        /// 首次渲染
        /// </summary>
        /// <param name="firstRender"></param>
        /// <returns></returns>
        protected override async Task OnAfterRenderAsync(bool firstRender)
        {
            if (firstRender)
            {
                try
                {
                    // 建立SIGNALR连接
                    _hubIo = new HubConnectionBuilder()
                        .WithUrl("http://localhost:5000/ioctlhub")
                        .WithAutomaticReconnect(new[] { TimeSpan.Zero, TimeSpan.FromSeconds(2), TimeSpan.FromSeconds(10) })
                        .Build();

                    await _hubIo.StartAsync();

                    // 注册查询端口状态响应函数
                    _hubIo.On<List<LoopItem>>("HandleLoopStatus", (tt) =>
                    {
                        _message = $" {DateTime.Now}  接收控制回路的状态";
                        InvokeAsync(StateHasChanged);
                    });

                    _hubIo.On<LoopItem>("HandleSingleLoop", (tt) =>
                    {
                        _loopItem = tt;
                        _message = $" {DateTime.Now}  接收单个控制回路[{CurrentLoopName}]的状态";
                        InvokeAsync(StateHasChanged);
                    });

                    _hubIo.On<List<string>>("HandleLoopName", (tt) =>
                    {
                        loopNameItems = tt.Select(c => new SelectedItem(c, c)).ToList();
                        if (_bFirst && tt.Count > 0)
                        {
                            _bFirst = false;
                            CurrentLoopName = tt[0];
                        }
                        _message = $" {DateTime.Now}  接收所有控制回路的名称";
                        InvokeAsync(StateHasChanged);
                    });

                    // 注册初始化传感器响应函数
                    _hubIo.On<string>("HandleInitLoops", (tt) =>
                    {
                        _message = tt;
                        InvokeAsync(StateHasChanged);
                    });

                    var timer = new System.Timers.Timer(1000);
                    timer.Elapsed += async (s, e) =>
                    {
                        try
                        {
                            await _hubIo.SendAsync("AcquireSingleLoop", CurrentLoopName);
                        }
                        catch (Exception ex)
                        {
                            _message = ex.Message;
                            await InvokeAsync(StateHasChanged);
                        }
                    };
                    timer.Start();

                    await _hubIo.SendAsync("AccquireLoopName");


                    _message = "SignalR连接成功";
                }
                catch (Exception ex)
                {
                    _message = ex.Message;
                }
                StateHasChanged();
            }
        }

        /// <summary>
        /// 初始化传感器
        /// </summary>
        /// <returns></returns>
        private async Task BtnInitLoop()
        {
            try
            {
                if (_hubIo != null && _hubIo.State == HubConnectionState.Connected)
                {
                    await _hubIo.SendAsync("InitialRegs");
                    await _hubIo.SendAsync("InitLoops");
                }
            }
            catch (Exception ex)
            {
                _message = ex.Message;
                await InvokeAsync(StateHasChanged);
            }
        }

        /// <summary>
        /// 卸载所有传感器
        /// </summary>
        /// <returns></returns>
        private async Task BtnUnloadLoop()
        {
            try
            {
                if (_hubIo != null && _hubIo.State == HubConnectionState.Connected)
                    await _hubIo.SendAsync("UnloadLoops");
            }
            catch (Exception ex)
            {
                _message = ex.Message;
                await InvokeAsync(StateHasChanged);
            }
        }

        /// <summary>
        /// 选择回路名称
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        private async Task SelectLoopHandle(SelectedItem item)
        {
            CurrentLoopName = item?.Text;
            _loopItem = null;
            StateHasChanged();
        }
    }
}
